package com.sctvcloud.zhaohua_sd.ui.fragment;

import android.content.Context;
import android.content.res.Configuration;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsoluteLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jiongbull.jlog.JLog;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.util.FloatVideoUtils2;
import com.ruihang.generalibrary.ui.util.IListData;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomRadioGroup;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.NetModeUtil;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.ruihang.ijkplaylib.widget.GPlayerView;
import com.sctvcloud.zhaohua_sd.R;
import com.sctvcloud.zhaohua_sd.application.Cache;
import com.sctvcloud.zhaohua_sd.application.Constances;
import com.sctvcloud.zhaohua_sd.beans.FChannel;
import com.sctvcloud.zhaohua_sd.beans.FProgram;
import com.sctvcloud.zhaohua_sd.beans.TvItem;
import com.sctvcloud.zhaohua_sd.beans.TvLivingList;
import com.sctvcloud.zhaohua_sd.http.AbsNetCallBack;
import com.sctvcloud.zhaohua_sd.http.NetUtils;
import com.sctvcloud.zhaohua_sd.ui.activities.NewesDetailActivity;
import com.sctvcloud.zhaohua_sd.ui.adapter.TVPagerAdapter;
import com.sctvcloud.zhaohua_sd.ui.dialog.NetModeDiaFragment;
import com.sctvcloud.zhaohua_sd.ui.utils.GSFPlayerScreenControllImp;
import com.sctvcloud.zhaohua_sd.ui.utils.GlideUtil;
import com.sctvcloud.zhaohua_sd.ui.utils.OnFullClick;
import com.sctvcloud.zhaohua_sd.ui.utils.SampleListener;
import com.sctvcloud.zhaohua_sd.ui.utils.SkipUtil;
import com.sctvcloud.zhaohua_sd.ui.utils.TVBottomControllerImp;
import com.sctvcloud.zhaohua_sd.ui.utils.TVTopControllerImp;
import com.sctvcloud.zhaohua_sd.ui.widget.BasePlayerView;
import com.shuyu.gsyvideoplayer.GSYVideoManager;
import com.shuyu.gsyvideoplayer.listener.INetPromt;
import com.shuyu.gsyvideoplayer.utils.OrientationUtils;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import org.xutils.common.util.LogUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import tv.danmaku.ijk.media.player.IMediaPlayer;

import static com.sctvcloud.zhaohua_sd.ui.dialog.NetModeDiaFragment.NO_TAG;
import static com.sctvcloud.zhaohua_sd.ui.dialog.NetModeDiaFragment.OK_TAG;

/**
 * Created by Administrator on 2017/7/13 0013.
 * 首页频道页
 */
public class TvFragment extends ColumnBaseFragment {
    @BindView(R.id.fragment_tv_img)
    protected CustomEXImageView img;
    @BindView(R.id.view_pager)
    protected ViewPager viewPager;
    @BindView(R.id.tab_layout)
    protected TabLayout tabLayout;
    @BindView(R.id.fragment_tv_img_play)
    protected ImageView play;

    private ColumnBaseFragment showingFragment;
    //    private TvLivingFragment tvLivingFragment;
//    private TvPageFragment tvPageFragment;
//    private TvChannelFragment tvChannelFragment;
//    private ProgramBackFragment programBackFragment;
//    private RadioFragment radioFragment;
//    private FragmentManager fragmentManager;
    private TVPagerAdapter adapter;

    private List<FChannel> radioChannel;
    private List<FChannel> channel;
    private String mProgramBackUrl;//该值为null代表尚未获取到url，为空串代表获取失败
    private String mAudioLookBackUrl;//广播回看数据

    private boolean mIsLoading = false;
    private boolean mIsProgramBackUrlRequesting = false;
    private String mVideoUrl;
    private List<TvItem> dataList = new ArrayList<>();
    private TvLivingList tvLivingList;
    /**
     * 卫视直播的url
     */
    private String liveUrl;

    private String liveImgUrl;

    private FloatVideoUtils2 floatVideoUtilss;
    private boolean isPortrait = true;
    @BindView(R.id.video_container)
    protected AbsoluteLayout videoContainer;
    private Handler handler;
    private TVTopControllerImp topController;
    private GSFPlayerScreenControllImp screenController;
    private TVBottomControllerImp bottomControllerImp;
    private NetModeDiaFragment netDiaFragment;
    private String titleTemp;
    private BasePlayerView videoPlayer;
    /**
     * 直播的标题缓存
     */
    private String liveTitleTemp;

    private boolean isPlayingWhenPause;

    private boolean isFirst = true;//是否第一次播放

    private OrientationUtils orientationUtils2;
    private int currentItem = 0;
    private IListData livingChannel;
    private boolean isRadio;
    private boolean isParentFragmentShow = true;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tv, container, false);
        ButterKnife.bind(this, view);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                int pos = tab.getPosition();
                if (tab.getPosition() == 0) {
                    if (!TextUtils.isEmpty(liveUrl)) {
                        if (!TextUtils.equals(liveUrl, mVideoUrl)) {
                            titleTemp = liveTitleTemp;
                        }
                    }
                }
                if (null != tab.getCustomView()) {
                    ((ImageView) (tab.getCustomView()).findViewById(R.id.tab_img)).setImageDrawable(getContext().getResources().getDrawable(dataList.get(pos).getSelectImg()));
                    ((TextView) (tab.getCustomView()).findViewById(R.id.tab_text)).setTextColor(getContext().getResources().getColor(R.color.colorRedMain));
                }
                currentItem = tab.getPosition();
                viewPager.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                Cache.getInstance().setHomeToAudio(false);
                int pos = (int) tab.getPosition();
                if (null != tab.getCustomView()) {
                    ((ImageView) (tab.getCustomView()).findViewById(R.id.tab_img)).setImageDrawable(getContext().getResources().getDrawable(dataList.get(pos).getNormalImg()));
                    ((TextView) (tab.getCustomView()).findViewById(R.id.tab_text)).setTextColor(getContext().getResources().getColor(R.color.colorTabColor));
                }
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        return view;
    }

    protected void initViews(View v, @Nullable Bundle savedInstanceState) {
//        group.setOnCheckedChangeListener(this);
        handler = new Handler();
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
//        fragmentManager = getChildFragmentManager();
        super.onViewCreated(view, savedInstanceState);

    }

    /**
     * 从Parent fragment判断是否显示的当前页
     *
     * @return
     */
    private boolean isThisPageShowing() {
        ColumnBaseFragment fragment = ((HomeFragment) getParentFragment()).getCurrentFragment();
        if (fragment instanceof TvFragment && isParentFragmentShow) {
            return true;
        }
        return false;
    }

    @Override
    public void onResume() {
        super.onResume();
//        isFront = true;
        //首次显示的时候，自动刷新数据
//        if (radioChannel == null || channel == null || TextUtils.isEmpty(mProgramBackUrl)
//                || channel.size() == 0 || radioChannel.size() == 0) {
//            //如果有一条数据为无效数据，则重新获取
////            getTvData();
//        }else
        if (floatVideoUtilss != null && isFront) {
            floatVideoUtilss.onResume();
        }
        if (isThisPageShowing()) {
            isFront = true;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (floatVideoUtilss != null) {
            if (isParentShowing && !hidden) {
                isParentFragmentShow = true;
                floatVideoUtilss.onResume();
            } else {
                isParentFragmentShow = false;
                floatVideoUtilss.onPause();
            }
        }
    }

    public void parentTitleClick() {
        if (videoPlayer != null) {
            //暂停播放
            if (videoPlayer.getCurrentState() == BasePlayerView.CURRENT_STATE_PLAYING) {
                isPlayingWhenPause = true;
            }
            videoPlayer.onVideoPause();
            videoPlayer.setOrientationChangeEnable(false);
            //暂停播放时，停止统计在线数据
            sendId = "";
            sendType = 0;
        }
    }

    @Override
    protected boolean onFragmentShow(boolean isFirst, boolean isCallFromResume) {
        isFront = true;
        if (tvLivingList == null || tvLivingList.getChannel() == null || tvLivingList.getChannel().size() == 0) {
            //如果有一条数据为无效数据，则重新获取
            getTvData();
        } else if (null != viewPager) {
            if (Cache.getInstance().isHomeToAudio()) {
                viewPager.setCurrentItem(1);
                Cache.getInstance().setHomeToAudio(false);
            } else {
                viewPager.setCurrentItem(currentItem);
            }
        }
        if (isFirst) {
            if (!TextUtils.isEmpty(mVideoUrl)) {
                playVideo(true, false);
            } else {
                if (img == null || img.getHeight() == 0) {
                    handler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            initVideoPlayer();
                        }
                    }, 300);
                } else {
                    initVideoPlayer();
                }
            }
        } else {
            if (floatVideoUtilss != null) {
                if (isPlayingWhenPause) {
                    floatVideoUtilss.onResume();
                }
            } else {
                if (videoPlayer != null) {
                    videoPlayer.onVideoResume();
                }
            }
        }

        if (null != livingChannel) {
            if (livingChannel instanceof FChannel) {
                setPlayMedia(livingChannel, isRadio);
            } else {
                setLookBackPlayMedia(livingChannel,isRadio);
            }
        }

        return super.onFragmentShow(isFirst, isCallFromResume);
    }

    @Override
    protected void onFragmentUnShowed(boolean isCallFromPause) {
        super.onFragmentUnShowed(isCallFromPause);
        //首页频道fragment页面切换离开
//        JLog.e("ddac  cal from pause  " + isCallFromPause + "  floatutil=" + floatVideoUtils);
        isFront = false;
        if (floatVideoUtilss != null) {
            if (floatVideoUtilss.isPlaying()) {
                JLog.e("ddac   will to pause");
                isPlayingWhenPause = true;
                floatVideoUtilss.onPause();
            }
        }
        if (videoPlayer != null && pauseType != 1) {
            //暂停播放
            if (videoPlayer.getCurrentState() == BasePlayerView.CURRENT_STATE_PLAYING) {
                isPlayingWhenPause = true;
            }
            videoPlayer.onVideoPause();
            videoPlayer.setOrientationChangeEnable(false);
            //暂停播放时，停止统计在线数据
            sendId = "";
            sendType = 0;

        }
        pauseType = 0;
        if (orientationUtils2 != null) {
            orientationUtils2.setEnable(false);
        }
    }

    private boolean isRequesting = false;

    int aaa = 0;

    /**
     * 获取频道相关数据
     */
    private void getTvData() {
        if (isRequesting) {
            return;
        }
        JLog.e("getTvData=" + channelUrl);
        if (TextUtils.isEmpty(channelUrl)) {
            toast(R.string.data_wrong);
            return;
        }
        aaa++;
        JLog.e("getTvData count=" + aaa);
        isRequesting = true;
        NetUtils.getNetAdapter().getTvLivingList(getOwnerName(), channelUrl, new AbsNetCallBack<TvLivingList>(TvLivingList.class) {
            @Override
            public void onSuc(TvLivingList tv) {
                JLog.e("getTvData=onSuconSuconSuc");
                if (tv != null) {
                    tvLivingList = tv;
                    initTvData(tv);
                }
            }

            @Override
            public void onError(Throwable ex, String errorMsg) {
                JLog.e("getTvData=onErro+" + errorMsg);
                super.onError(ex, errorMsg);
            }

            @Override
            public void onEnd() {
                super.onEnd();
                JLog.e("getTvData=onEnd+");
                isRequesting = false;
            }
        });

    }

    private void initTvData(TvLivingList tvLivingList) {
        channel = tvLivingList.getChannel();
        radioChannel = tvLivingList.getAudioChannel();
        mProgramBackUrl = tvLivingList.getLookbackUrl();
        mAudioLookBackUrl  = tvLivingList.getGuangbodiantai();
        if (Cache.getInstance().isHomeToAudio() && ListUtils.isListValued(radioChannel)) {
            getTvLivingData(radioChannel.get(0), true);
        } else if (ListUtils.isListValued(channel)) {
            getTvLivingData(channel.get(0), false);
        }
        dataList.clear();
        TvItem item1 = new TvItem("电视频道", TVPagerAdapter.TYPE_TV,
                R.mipmap.icon_tv_play_press, R.mipmap.icon_tv_play_normal, channel, "");
        TvItem item2 = new TvItem("广播电台", TVPagerAdapter.TYPE_VIDEO,
                R.mipmap.icon_tv_fm_press, R.mipmap.icon_tv_fm_normal, radioChannel, mAudioLookBackUrl);
        TvItem item3 = new TvItem("节目回放", TVPagerAdapter.TYPE_BACK,
                R.mipmap.icon_tv_history_press, R.mipmap.icon_tv_history_normal, null, mProgramBackUrl);
        dataList.add(item1);
        dataList.add(item2);
        dataList.add(item3);
        if (null == adapter) {
            adapter = new TVPagerAdapter(getContext(), this, getActivity().getSupportFragmentManager(), dataList);
            viewPager.setAdapter(adapter);
            tabLayout.setupWithViewPager(viewPager);
            tabLayout.setTabMode(TabLayout.MODE_FIXED);
        } else {
            adapter.setData(dataList);
        }
        adapter.notifyDataSetChanged();
        initTabData(dataList);

    }

    private void initTabData(List<TvItem> dataList) {
        for (int i = 0; i < dataList.size(); i++) {
            TabLayout.Tab tab = tabLayout.getTabAt(i);
            //注意！！！这里就是添加我们自定义的布局
            tab.setCustomView(adapter.getTabView(i));
            LinearLayout linearLayout = (LinearLayout) tabLayout.getChildAt(0);
            linearLayout.setDividerPadding(30);
            linearLayout.setShowDividers(LinearLayout.SHOW_DIVIDER_MIDDLE);
            linearLayout.setDividerDrawable(ContextCompat.getDrawable(getContext(), R.drawable.layout_divider_vertical));
            if (null != tab.getCustomView()) {
                ((ImageView) (tab.getCustomView()).findViewById(R.id.tab_img)).setImageDrawable(getContext().getResources().getDrawable(dataList.get(i).getNormalImg()));
                ((TextView) (tab.getCustomView()).findViewById(R.id.tab_text)).setTextColor(getContext().getResources().getColor(R.color.colorTabColor));
            }
            //这里是初始化时，默认item0被选中，setSelected（true）是为了给图片和文字设置选中效果，代码在文章最后贴出
            if (i == 0) {
                ((ImageView) (tab.getCustomView()).findViewById(R.id.tab_img)).setImageDrawable(getContext().getResources().getDrawable(dataList.get(0).getSelectImg()));
                ((TextView) (tab.getCustomView()).findViewById(R.id.tab_text)).setTextColor(getContext().getResources().getColor(R.color.colorRedMain));
            }
        }
        if (Cache.getInstance().isHomeToAudio()) {
            viewPager.setCurrentItem(1);
        } else {
            viewPager.setCurrentItem(0);
        }
    }

    @Override
    public boolean hasShowPlayer() {
        return videoPlayer != null && videoPlayer.getVisibility() == View.VISIBLE;
    }

//    @Override
//    public void onTabSelected(TabLayout.Tab tab) {
//        if (tab.getPosition() == 0) {
//            if (!TextUtils.isEmpty(liveUrl)) {
//                if (!TextUtils.equals(liveUrl, mVideoUrl)) {
//                    titleTemp = liveTitleTemp;
////                    setVideoPlayer(liveUrl);
//                }
//            }
//        }
//
//    }
//
//    @Override
//    public void onTabUnselected(TabLayout.Tab tab) {
//    }
//
//    @Override
//    public void onTabReselected(TabLayout.Tab tab) {
//    }

    @Override
    public void onDestroyView() {
        if (tabLayout != null) {
            tabLayout.removeAllTabs();
        }
        if (floatVideoUtils != null) {
            floatVideoUtils.onDestory();
        }
        if (orientationUtils2 != null) {
            orientationUtils2.releaseListener();
        }
        if (null != RHTask) {
            RHTask.cancel();
            RHTask = null;
        }
        if (null != readyOnlineTimer) {
            readyOnlineTimer.cancel();
            readyOnlineTimer.purge();
            readyOnlineTimer = null;
        }
        super.onDestroyView();
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);

    }

    @OnClick(value = {R.id.fragment_tv_img_play})
    public void click(View view) {
        if (TextUtils.isEmpty(mVideoUrl)) {
            toast("数据错误");
            return;
        }
//        playVideo();
    }


    private void getProgramBackData() {
        mIsProgramBackUrlRequesting = false;
//        if (viewPager.getCurrentItem() == 1) {
//            ((ProgramBackFragment) tvAdapter.getItem(1)).getFirstList();
//        }
//        else {
//            ((ProgramBackFragment) tvAdapter.getItem(1)).setIsLoading(false);
//        }
    }

    public void requestProgramBackUrl() {
        if (mIsLoading || mProgramBackUrl == null) {
            mIsProgramBackUrlRequesting = true;
        } else {
            getProgramBackData();
        }
    }

    public void setLoadingState(boolean isLoading) {
        mIsLoading = isLoading;
    }

    public String getProgramBackUrl() {
        return mProgramBackUrl;
    }

    public void setData(String programBackUrl, String id, String title, String videoUrl) {
        mProgramBackUrl = programBackUrl;
//        tv_title.setText(TextUtils.isEmpty(title) ? getString(R.string.default_title) : title);
        JLog.e("dada=" + videoUrl);
        liveUrl = videoUrl;
        setVideoPlayer(videoUrl, false, false);
        titleTemp = title;
        liveTitleTemp = title;

        if (topController != null) {
            topController.setTitle(titleTemp);
        }


        if (mIsProgramBackUrlRequesting) {
            getProgramBackData();
        }
    }

    public String getChannelUrl() {
        return channelUrl;
    }

    private boolean setVideoPlayer(String videoUrl, boolean isLiving, boolean isRadio) {
        this.isRadio = isRadio;
        mVideoUrl = videoUrl;
        // if (NetUtils.isWifiConnected(getContext())) {
        if (isFront) {
            if (null != livingChannel && isLiving) {
                FChannel fc = (FChannel) livingChannel;
                sendId = fc.getChannelId();
                int resourceType = 0;
                if (isRadio) {
                    sendType = 3;
                    resourceType = 6;
                } else {
                    resourceType = 5;
                    sendType = 2;
                }
                if (!lastSendId.equalsIgnoreCase(sendId)) {
                    lastSendId = sendId;
                    SkipUtil.skipToAddUserOperate(getContext(), getOwnerName(), resourceType, 0, "频道/广播 播放", sendId, Cache.getInstance().getCurrentChannelId());
                }
            } else {
                sendId = "";
                sendType = 0;
            }
            playVideo(isLiving, isRadio);
            return true;
        }
        return false;
        //}
    }

    private void playVideo(boolean isLiving, boolean isRadio) {
        int netType = NetModeUtil.GetNetype(getContext());
        boolean haseCallstop = false;
        if (getContext() == null) {
            return;
        }
        if (initVideoPlayer()) {
//            bottomController.initInfo(liveInfo);
            if (orientationUtils2 == null) {
//                orientationUtils2 = new OrientationUtils(getActivity(), videoPlayer);
//                orientationUtils2.setRotateWithSystem(false);
            }
//            orientationUtils.setEnable(false);
            haseCallstop = true;
        } else {
//            if (TextUtils.equals(mVideoUrl, floatVideoUtils.getPlayerView().getCurrentUrl())) {
//                floatVideoUtils.stopVideoView();
//                haseCallstop = true;
//            }
            haseCallstop = false;
        }
//        boolean isLiving = TextUtils.equals(mVideoUrl, liveUrl);
        videoPlayer.setLiving(isLiving);
        videoPlayer.setRadio(isRadio);
        videoPlayer.setThumbPlay(isRadio);
        if (isFirst) {
            videoPlayer.setMute(false);
//            AudioManager mAudioManager = (AudioManager) getContext().getSystemService(Context.AUDIO_SERVICE);
//            mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, 0, 1);
//          int  max = mAudioManager.getStreamMaxVolume( AudioManager.STREAM_MUSIC );
//            int current = mAudioManager.getStreamVolume( AudioManager.STREAM_MUSIC );
//            JLog.e("AudioManager","---max = "+max+" current = "+current);
        }

        if (isLiving && videoPlayer.getThumbImge() != null) {
            GlideUtil.getGlideWithLarge169DefNotFit(getContext(), liveImgUrl).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(videoPlayer.getThumbImge());
        }
        videoPlayer.setUp(mVideoUrl, false, titleTemp);
        if (netType == 1) {
//            if (isFirst) {
//                videoPlayer.setMute(true);
//            }
            if (isFront) {
                videoPlayer.startPlay();
            }
//            if (haseCallstop) {
//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
////                        floatVideoUtils.setLiving(TextUtils.equals(mVideoUrl, liveUrl)).play(img, mVideoUrl);
//                        videoPlayer.startPlayLogic();
//                    }
//                }, 700);
//            } else {
//                floatVideoUtils.setLiving(TextUtils.equals(mVideoUrl, liveUrl)).play(img, mVideoUrl);
//                videoPlayer.setUp(mVideoUrl, false, titleTemp);
//                if (topController != null) {
//                    topController.setTitle(titleTemp);
//                }
//            }
        }
        isFirst = false;

    }

    private void showNetProt() {
        if (Cache.getInstance().isCheckNet()) {
            videoPlayer.startPlayLogic();
            return;
        }
        if (netDiaFragment == null) {
            netDiaFragment = new NetModeDiaFragment();
        }
        if (!netDiaFragment.isAdded()&&!netDiaFragment.isShow()) {
            netDiaFragment.setCallBack(netBack);
            netDiaFragment.show(getChildFragmentManager(), NET_TAG);
        }
    }

    private synchronized boolean initVideoPlayer() {
        JLog.e("jjaj   c=" + getContext());
        if (getContext() == null) {
            return false;
        }
        JLog.e("jjaj    img h=" + img.getHeight());
        if (floatVideoUtilss == null) {
            floatVideoUtilss = new FloatVideoUtils2(getContext(), img, videoContainer, 0, true);
            if (videoPlayer == null) {
                videoPlayer = new BasePlayerView(getContext());
                videoPlayer.setOnPlayerStatusListener(new BasePlayerView.OnPlayerStatusChanged() {
                    @Override
                    public void OnPlaying() {
                        //加载完成时如果栏目已经切换离开，直接暂停播放
                        if (!isFront) {
                            videoPlayer.onVideoPause();
                        }
                    }

                    @Override
                    public void OnError() {

                    }

                    @Override
                    public void OnStop() {

                    }

                    @Override
                    public void OnEnd() {

                    }
                });
                JLog.e("vvav  tv player has created");
                videoPlayer.setLiving(true);
                videoPlayer.setNetPromt(new INetPromt() {
                    @Override
                    public boolean onNetPromt() {
                        showNetProt();
                        return false;
                    }
                });
                videoPlayer.setFullClick(new OnFullClick() {
                    @Override
                    public void onFullClick(StandardGSYVideoPlayer player, boolean isLandscape) {
                        JLog.e("rrsr player=" + player + "   islandscape=" + isLandscape);
                        if (isLandscape) {
                            if (orientationUtils2 != null) {
                                orientationUtils2.resolveByClick();
                                orientationUtils2.backToProtVideo();
                            } else {
                                actionToPortrait();
                            }
                            StandardGSYVideoPlayer.backFromWindowFull(getContext());
                        } else {
                            if (orientationUtils2 != null) {
                                orientationUtils2.resolveByClick();
                            } else {
                                actionToLandscape();
                            }
                            //第一个true是否需要隐藏actionbar，第二个true是否需要隐藏statusbar
//                            player.startWindowFullscreen(getContext(), false, false);
                        }
                    }
                });
                videoPlayer.setStandardVideoAllCallBack(new SampleListener() {
                    @Override
                    public void onPrepared(String url, Object... objects) {
                        super.onPrepared(url, objects);
                        if (orientationUtils2 != null) {
                            orientationUtils2.setEnable(true);
                        }
                    }

                    @Override
                    public void onQuitFullscreen(String url, Object... objects) {
                        super.onQuitFullscreen(url, objects);
//                        JLog.e("qqaq  state=" + videoPlayer.getCurrentState() + "    " + objects[1]);
                        if (orientationUtils2 != null) {
                            JLog.e("ttat  " + orientationUtils2.isEnable() + "   " + orientationUtils2.isRotateWithSystem() + "   " + videoPlayer.getOrientationUtils());
                        }
                    }
                });
                videoPlayer.setOnCompletionListener(new IMediaPlayer.OnCompletionListener() {
                    @Override
                    public void onCompletion(IMediaPlayer iMediaPlayer) {
                        LogUtil.e("videoPlayer----------onCompletion--");
                        if (null != livingChannel && isRadio) {
                            LogUtil.e("videoPlayer----------onCompletion--reset");
                            setPlayMedia(livingChannel, isRadio);
                        }
                    }
                });
                floatVideoUtilss.setPlayerView(videoPlayer);
            }
            floatVideoUtilss.showPlayer(img, false);

            return true;
        }
        return false;
    }

    private void onChangeToPlaying() {
    }

    private void onChangeToStop() {
    }

    private void onPlayerConstructor(GPlayerView playerView, ViewGroup base) {
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (floatVideoUtilss != null) {
            isPortrait = newConfig.orientation == Configuration.ORIENTATION_PORTRAIT;
            if (isPortrait) {
//                floatVideoUtils.getPlayerView().setForbidGestureScroll(true);
                floatVideoUtilss.setScrolledY(getCurrentScrollY());
                floatVideoUtilss.onChangeToPortrait();
//                onChangedToPortrait(newConfig);
            } else {
//                onChangedToLandscape(newConfig);
                floatVideoUtilss.onChangeToPortraitLandscape();
//                floatVideoUtils.getPlayerView().setForbidGestureScroll(false);
            }
//            floatVideoUtils.onConfigurationChangedEnd(newConfig);
        }
        if (videoPlayer != null && isFront) {
            videoPlayer.onConfigurationChanged(getActivity(), newConfig, orientationUtils2);
        }
    }

    protected int getCurrentScrollY() {
        return 0;
    }

    protected void onChangedToPortrait(Configuration newConfig) {
    }

    protected void onChangedToLandscape(Configuration newConfig) {
        if (videoPlayer != null) {
//            JLog.e("GSYVideoPlayer  " + videoPlayer.getFullWindowPlayer() + "\n " + videoPlayer);
//            JLog.e("rrsr  " + videoPlayer.getFullWindowPlayer() + "\n " + videoPlayer + "   " + orientationUtils.isClickLand());
        }
    }

    private int pauseType = 0;//-1 非收音机   1为收音机

    @Override
    public void onPause() {
        if (!isRadio) {
            if (floatVideoUtilss != null) {
                floatVideoUtilss.onPause();
            }
            pauseType = -1;
        } else {
            pauseType = 1;
        }
        super.onPause();
//        isFront = false;
    }

    @Override
    public boolean onBackPressed() {
        JLog.e("float VideoUtils " + floatVideoUtilss);
//        if (floatVideoUtils == null || !floatVideoUtils.onBackPress()) {
//            return false;
//        }
//        if (videoPlayer==null || orientationUtils.b)
        if (orientationUtils2 != null) {
            orientationUtils2.backToProtVideo();
        }
        if (StandardGSYVideoPlayer.backFromWindowFull(getContext())) {
            if (orientationUtils2 == null) {
                actionToPortrait();
            }
            return true;
        }
        return super.onBackPressed();
    }

    @Override
    public void onDestroy() {
        if (floatVideoUtilss != null) {
            floatVideoUtilss.onDestory();
        }
        if(null!=adapter) {
            adapter.clear(viewPager);
        }
        super.onDestroy();
    }

//    public int getCurrentSelectedIndex() {
//        return viewPager.getCurrentItem();
////    }

    /**
     * 确定使用移动网络播放的回调，开始播放
     */
    BaseDialogFragment.ICallBack netBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            if (msg.what == NO_TAG) {
//                floatVideoUtils.stopVideoView();
            } else if (msg.what == OK_TAG) {
//                floatVideoUtils.setLiving(false).play(img, mVideoUrl);
//                if (topController != null) {
//                    topController.setTitle(titleTemp);
//                }
                Cache.getInstance().setCheckNet(true);
                videoPlayer.startPlayLogic();
            }
        }
    };


    public List<FChannel> getChannel() {
        return channel;
    }

    private void getTvLivingData(FChannel fchannel, boolean isRadio) {
        if (!TextUtils.isEmpty(fchannel.getLiveUrl())) {
            liveUrl = fchannel.getLiveUrl();
            livingChannel = fchannel;
        }
        if (!TextUtils.isEmpty(fchannel.getChannelName())) {
            titleTemp = fchannel.getChannelName();
            liveTitleTemp = fchannel.getChannelName();
        }
        liveImgUrl = fchannel.getDataImg();
        if (topController != null) {
            topController.setTitle(titleTemp);
        }
        //TODO 启动直播在线统计
        startOnlineService(handlerOnline);
        setVideoPlayer(liveUrl, true, isRadio);
    }


    public void setLookBackPlayMedia(IListData fProgram,boolean isRadio) {
        livingChannel = fProgram;
        this.isRadio = isRadio;
        FProgram fp = (FProgram) fProgram;
        String title = fp.getProgrammeTitle();
//        tv_title.setText(title);
        if (!TextUtils.isEmpty(fp.getProgrammeUrl())) {
            mVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, fp.getProgrammeUrl());
            titleTemp = fp.getProgrammeTitle();
//            playVideo();
            if (setVideoPlayer(mVideoUrl, false, isRadio)) {
                int netType = NetModeUtil.GetNetype(getContext());
                if (videoPlayer.getThumbImge() != null) {
                    GlideUtil.getGlideWithLarge169DefNotFit(getContext(), fp.getProgrammeImage()).skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE).into(videoPlayer.getThumbImge());
                }
                JLog.e("bbab  net type=" + netType + "  img=" + fp.getProgrammeImage());
                if (netType == 1) {
                    if (floatVideoUtilss != null && videoPlayer != null) {
                        videoPlayer.setRadio(isRadio);
                        videoPlayer.startPlay();
                    }
                }
            }
        } else {
            // toast("播放地址为空");
        }
    }

    public void setPlayMedia(IListData channel, boolean isRadio) {
        if (channel == null) {
            toast("无效播放地址");
            return;
        }

        livingChannel = channel;
        this.isRadio = isRadio;
        FChannel fc = (FChannel) channel;
        String title = fc.getChannelName();
//        tv_title.setText(title);
        if (!TextUtils.isEmpty(fc.getLiveUrl())) {
            mVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, fc.getLiveUrl());
            titleTemp = fc.getChannelName();
//            playVideo();
            if (setVideoPlayer(mVideoUrl, true, isRadio)) {
                int netType = NetModeUtil.GetNetype(getContext());
                if (videoPlayer.getThumbImge() != null) {
                    GlideUtil.getGlideWithLarge169DefNotFit(getContext(), fc.getChannelImage()).into(videoPlayer.getThumbImge());
                }
//                JLog.e("bbab  net type=" + netType + "  img=" + fProgram.getProgrammeImage());
                if (netType == 0) {
                    if (floatVideoUtilss != null && videoPlayer != null) {
                        videoPlayer.setLiving(true);
                        videoPlayer.setRadio(isRadio);
                        videoPlayer.startPlay();
                        floatVideoUtilss.onResume();
                    }
                }
            }
        } else {
            toast("播放地址为空");
        }


    }

    private boolean isInitListener = false;

    /**************************直播在线日志统计******************************/


    Handler handlerOnline = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg != null && msg.what == 22) {
                sendOnlineMsg();
            }
        }
    };
    private Timer readyOnlineTimer;
    private TimerTask RHTask;
    private String sendId = "";
    private String lastSendId = "";
    private int sendType = 0;

    /**
     * 启动直播统计心跳
     *
     * @param mHandler
     */
    public void startOnlineService(final Handler mHandler) {
        long HeartbeatTime = 60 * 1000;//心跳时间
        if (null == readyOnlineTimer) {
            try {
                readyOnlineTimer = new Timer(true);
                java.util.Date d1 = new java.util.Date();
                if (null == RHTask) {
                    RHTask = new TimerTask() {
                        @Override
                        public void run() {
                            Message msg = new Message();
                            msg.what = 22;
                            mHandler.sendMessage(msg);
                        }
                    };
                }
                readyOnlineTimer.schedule(RHTask, d1, HeartbeatTime);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 向服务器发送日志
     */
    private void sendOnlineMsg() {
        if (!TextUtils.isEmpty(sendId)) {
            SkipUtil.skipToAddOnline(getContext(), getOwnerName(), sendId, sendType);
        }
    }


    /****************************************************************************/
//    @Override
//    public void onCheckedChanged(CustomRadioGroup group, int checkedId) {
//        ArrayList<Pair<String, String>> pairs = new ArrayList<>();
//        pairs.add(new Pair<>("页面", "首页"));
//        pairs.add(new Pair<>("栏目", "频道"));
//        pairs.add(new Pair<>("行为类型", "点击"));
//        ColumnBaseFragment fragment;
//        isInitListener = false;
//        switch (checkedId) {
//            case R.id.rb_tv_fm:
//                if (radioFragment == null) {
//                    radioFragment = new RadioFragment();
//                }
//                fragment = radioFragment;
//                pairs.add(new Pair<>("位置", "广播电台"));
//                break;
//            case R.id.rb_tv_history:
//                if (programBackFragment == null) {
//                    programBackFragment = new ProgramBackFragment();
//                }
//                fragment = programBackFragment;
//                pairs.add(new Pair<>("位置", "节目回看"));
//
//                break;
//            case R.id.rb_tv_play:
//                if (tvChannelFragment == null) {
//                    tvChannelFragment = new TvChannelFragment();
//                }
//                tvChannelFragment.setData(channel);
//                fragment = tvChannelFragment;
//                pairs.add(new Pair<>("位置", "电视直播"));
//                if (isFirst) {
//                    isInitListener = true;
//                } else {
//                    isInitListener = false;
//                }
//                break;
//            default:
//                if (radioFragment == null) {
//                    radioFragment = new RadioFragment();
//                }
//                fragment = radioFragment;
//                break;
//        }
//        if (!isInitListener) {
//            GridsumWebDissector.getInstance().trackEvent(fragment, "", "卫视", "", 200, pairs);
//        }
//
//        showFragment(fragment);
//    }


//    private void showFragment(final ColumnBaseFragment fragment) {
//        if (fragment == null || showingFragment == fragment) {
//            JLog.e("show fragment faile fragment :" + fragment + "  showingFragment:" + showingFragment);
//            return;
//        }
//        FragmentTransaction ft = fragmentManager.beginTransaction();
//        if (showingFragment != null && showingFragment.isAdded()) {
//            ft.hide(showingFragment);
//        }
//
//        if (fragment.isAdded()) {
//            ft.show(fragment);
//        } else {
//            ft.add(R.id.main_content, fragment);
//        }
//        ft.commitAllowingStateLoss();
////        ft.commit();
//        showingFragment = fragment;
//        JLog.e("show fragment->" + fragment);
//    }


}
